<template>
  <div class="h-full flex flex-col bg-zinc-100">
    <!-- Main Content -->
    <div class="projects-window h-full p-4 md:p-6 flex-1 overflow-y-auto">
      <!-- Loading State -->
      <div v-if="loading" class="flex items-center justify-center h-full">
        <div class="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-zinc-300 mr-2"></div>
        <p>Fetching projects...</p>
      </div>

      <!-- Error State -->
      <div v-else-if="error" class="flex flex-col items-center justify-center h-full text-zinc-600">
        <h3>Something went wrong!</h3>
        <p>{{ error }}</p>
        <button class="bg-zinc-200 hover:bg-zinc-300 text-zinc-800 pb-1 px-4 rounded mt-4" @click="fetchRepos">
          Try Again
        </button>
      </div>

      <!-- Empty State -->
      <div v-else-if="!loading && repos.length === 0"
        class="flex flex-col items-center justify-center h-full text-zinc-600">
        <h3>No pinned projects found</h3>
      </div>

      <div class="projects-grid grid grid-cols-1 md:grid-cols-2 gap-6">
        <div v-for="repo in repos" :key="repo.id" class="project-card" :data-index="repo.id" ref="projectCardRefs">
          <div
            class="project-card-inner bg-zinc-50 rounded-xl border border-zinc-200 shadow-sm overflow-hidden transition-all hover:shadow-md h-full flex flex-col">
            <div class="p-5 flex-1">
              <div class="flex justify-between items-start mb-4">
                <div>
                  <h3 class="text-lg font-semibold text-zinc-800">{{ repo.name }}</h3>
                  <div class="flex items-center gap-2 mt-1">
                    <span class="text-xs text-zinc-500 flex items-center gap-1">
                      {{ repo.language }}
                    </span>
                  </div>
                </div>
                <!-- Link Container -->
                <div class="flex gap-1 -mr-1">
                  <a v-if="repo.html_url" :href="repo.html_url" target="_blank" rel="noopener noreferrer"
                    class="text-zinc-500 hover:text-zinc-700 transition-colors p-1 -mr-1" title="GitHub Repository">
                    <svg v-once xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24"
                      fill="currentColor">
                      <path
                        d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
                    </svg>
                  </a>
                  <!-- Demo Link -->
                  <a v-if="repo.homepage" :href="repo.homepage" target="_blank" rel="noopener noreferrer"
                    class="text-zinc-500 hover:text-zinc-700 transition-colors p-1" title="Live Demo">
                    <svg v-once xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24"
                      fill="currentColor">
                      <path
                        d="M19 19H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z" />
                    </svg>
                  </a>
                </div>
              </div>

              <p class="text-zinc-600 text-sm mb-4">{{ repo.description }}</p>

              <div class="flex flex-wrap gap-2 mb-4">
                <span v-for="topic in repo.topics.slice(0, 4)" :key="topic"
                  class="text-xs px-2 py-1 rounded-full bg-zinc-100 text-zinc-700">
                  {{ topic }}
                </span>
                <span v-if="repo.topics.length > 4" class="text-xs px-2 py-1 rounded-full bg-zinc-100 text-zinc-700">
                  +{{ repo.topics.length - 4 }} more </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Status Bar -->
    <div
      class="flex items-center justify-between px-3 py-1 text-xs text-zinc-500 bg-zinc-50/90 border-t border-zinc-300">
      <div>Showing {{ repos.length }} projects</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onMounted, nextTick } from "vue";
import gsap from "gsap";

import type { Repository } from "@/types";

// State variables
const loading = ref<boolean>(false);
const repos = ref<Repository[]>([]);
const error = ref<string | null>(null);

// Manually define what repos to fetch
const pinnedRepoNames = ["chenxing-dev.github.io", "linux-distro-quiz", "drink-tier-list", "blog"]

// Fetch repositories from GitHub
const fetchRepos = async () => {
  loading.value = true;
  error.value = null;

  try {
    // Use GitHub REST API to fetch user repositories
    const response = await fetch("https://api.github.com/users/chenxing-dev/repos?sort=updated&per_page=20");
    if (!response.ok) {
      throw new Error(`Error: ${response.status} ${response.statusText}`);
    }
    let data = await response.json();

    // Filter to only include the manually defined pinned repos
    data = data.filter((repo: Repository) => pinnedRepoNames.includes(repo.name));

    // Map to include only necessary fields
    repos.value = data.map((repo: Repository) => ({
      id: repo.id,
      name: repo.name,
      description: repo.description,
      topics: repo.topics,
      html_url: repo.html_url,
      homepage: repo.homepage,
      language: repo.language
    }));
  } catch (err: any) {
    error.value = err.message || "An unknown error occurred.";
  } finally {
    loading.value = false;
  }
};

// DOM node refs don't need deep reactivity
const projectCardRefs = shallowRef<HTMLElement[]>([]);

onMounted(async () => {
  await fetchRepos();
  await nextTick();

  // Initialize animations
  projectCardRefs.value.forEach((card, index) => {
    // Set initial state
    gsap.set(card, {
      opacity: 0,
      y: 30
    });

    // Create animation timeline
    const tl = gsap.timeline({});

    // Animate card entry
    tl.to(card, {
      opacity: 1,
      y: 0,
      duration: 0.6,
      ease: "back.out(1.4)",
      delay: index * 0.1
    });

    // Add subtle stagger effect to inner elements
    tl.fromTo(
      card.querySelectorAll("h3, p, span"),
      {
        opacity: 0,
        y: 10
      },
      {
        opacity: 1,
        y: 0,
        stagger: 0.05,
        duration: 0.3
      },
      "<0.2"
    );
  });
});
</script>

<style scoped>
.projects-window {
  scrollbar-color: #71717a #e4e4e7;
  scrollbar-width: thin;
}

.project-card-inner {
  transform-style: preserve-3d;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  transform: translateZ(0);
}

.project-card:hover .project-card-inner {
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
}
</style>
